package cn.jasonone.him;

import java.lang.management.ManagementFactory;

import javax.annotation.Resource;
import javax.management.InstanceAlreadyExistsException;
import javax.management.MBeanRegistrationException;
import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.NotCompliantMBeanException;
import javax.management.ObjectName;

import org.apache.catalina.util.ServerInfo;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.ContextStartedEvent;
import org.springframework.context.event.EventListener;

import com.corundumstudio.socketio.AckRequest;
import com.corundumstudio.socketio.AuthorizationListener;
import com.corundumstudio.socketio.Configuration;
import com.corundumstudio.socketio.HandshakeData;
import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.SocketIOServer;
import com.corundumstudio.socketio.Transport;
import com.corundumstudio.socketio.annotation.SpringAnnotationScanner;
import com.corundumstudio.socketio.listener.ConnectListener;
import com.corundumstudio.socketio.listener.DataListener;
import com.corundumstudio.socketio.listener.DisconnectListener;

import cn.jasonone.him.jmx.HimJMXServer;
import cn.jasonone.him.jmx.HimMBean;
import cn.jasonone.him.model.HimUserInfo;
import cn.jasonone.him.model.Message;
import cn.jasonone.him.service.HimService;
import cn.jasonone.him.util.ServerUtil;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@org.springframework.context.annotation.Configuration
@ComponentScan("cn.jasonone.him")
public class HimAutoConfig {
	@Resource
	private SocketIOServer server;
	@Resource
	private HimProperties himProperties;
	@Resource
	private HimJMXServer jmxServer;

	@EventListener
	public void closed(ContextClosedEvent e) {
		log.info("正在停止服务,停止端口为:{}", himProperties.getPort());
		server.stop();
	}

	@Bean
	public SocketIOServer socketIOServer(HimService himService, HimProperties himProperties,ApplicationContext applicationContext) {
		SocketIOServer server = ServerUtil.createServer(himProperties, himService, applicationContext);
		server.start();
		return server;
	}

	@EventListener
	public void init(ContextRefreshedEvent e) {
		jmxServer.start();
	}

	@Bean
	public SpringAnnotationScanner springAnnotationScanner(SocketIOServer server) {
		return new SpringAnnotationScanner(server);
	}

	@Bean
	@ConditionalOnMissingBean(HimService.class)
	public HimService himService() {
		log.warn("未找到自定义HimService的实现类,将使用默认实现");
		return new HimService() {
		};
	}
}
